/*
 * @lc app=leetcode.cn id=236 lang=java
 *
 * [236] 二叉树的最近公共祖先
 */

// @lc code=start
/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
class Solution {
    TreeNode res;
    public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
        res=new TreeNode();
        dfs(root,p,q);
        return res;
    }
    public boolean dfs(TreeNode root,TreeNode p,TreeNode q){
        if(root==null)return false;
        boolean flson=dfs(root.left,p,q);
        boolean frson=dfs(root.right,p,q);
        if(flson&&frson||(root==p||root==q&&(flson||frson))){
            res=root;
            return true;
        }
        return flson||frson||root==q||root==p;
    }

}
// @lc code=end

